package cn.dubito.seller.service;

import cn.dubito.entity.Order;
import cn.dubito.entity.Product;
import cn.dubito.entity.enums.OrderStatusEnum;
import cn.dubito.entity.enums.OrderTypeEnum;
import cn.dubito.seller.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.UUID;

/**
 * @author liliang
 * @description: 订单服务接口
 * @date 2018/5/29.
 */
@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRpcService productRpcService;

    /**
     * 申购订单
     *
     * @param order
     * @return
     */
    public Order apply(Order order) {
        checkOrder(order);
        // 完善订单数据
        completeOrder(order);
        order = orderRepository.saveAndFlush(order);
        return order;
    }

    /**
     * 完善订单数据
     *
     * @param order 订单
     */
    private void completeOrder(Order order) {
        order.setOrderId(UUID.randomUUID().toString().replaceAll("-", ""));
        order.setOrderType(OrderTypeEnum.APPLY.name());
        order.setOrderStatus(OrderStatusEnum.SUCCESS.name());
        order.setUpdateAt(new Date());
    }

    /**
     * 校验订单数据
     *
     * @param order order
     */
    private void checkOrder(Order order) {
        Assert.notNull(order, "订单不可以为空");
        Assert.notNull(order.getOuterOrderId(), "需要外部订单 ID");
        Assert.notNull(order.getChanId(), "需要渠道编号");
        Assert.notNull(order.getChanUserId(), "需要用户 ID");
        Assert.notNull(order.getProductId(), "需要产品编号");
        Assert.notNull(order.getAmount(), "需要购买金额");
        Assert.notNull(order.getCreateAt(), "需要创建订单时间");

        // 产品金额是否符合需求
        Product product = productRpcService.findOne(order.getProductId());
        Assert.notNull(product, "产品不存在");
        Assert.isTrue(order.getAmount().compareTo(product.getThresholdAmount()) > 0, "购买金额不正确");
    }
}
